<template>
  <div class="content-editor">
    <div class="editor-header">
      <h3 class="editor-title">
        <el-icon><Edit /></el-icon>
        内容编辑
      </h3>
      <div class="editor-actions">
        <el-button 
          type="primary" 
          :icon="View"
          @click="togglePreview"
        >
          {{ showPreview ? '隐藏预览' : '显示预览' }}
        </el-button>
      </div>
    </div>
    
    <div class="editor-content">
      <!-- 图片选择 -->
      <div class="content-section">
        <div class="section-header">
          <h4>选择图片</h4>
          <el-button 
            text 
            size="small"
            @click="showImageSelector"
          >
            更换图片
          </el-button>
        </div>
        
        <div class="image-selection">
          <div v-if="selectedImage" class="selected-image-card">
            <img :src="selectedImage.fileUrl" :alt="selectedImage.originalName" />
            <div class="image-info">
              <div class="image-name">{{ selectedImage.originalName }}</div>
              <div class="image-size">{{ selectedImage.width }}×{{ selectedImage.height }}</div>
            </div>
          </div>
          <div v-else class="no-image-placeholder" @click="showImageSelector">
            <el-icon size="32"><Plus /></el-icon>
            <span>点击选择图片</span>
          </div>
        </div>
      </div>
      
      <!-- 文字内容编辑 -->
      <div class="content-section">
        <div class="section-header">
          <h4>文字内容</h4>
          <el-button 
            text 
            size="small"
            @click="showTextGenerator"
          >
            AI生成文案
          </el-button>
        </div>
        
        <div class="text-areas">
          <div
            v-for="(textArea, index) in textAreas"
            :key="index"
            class="text-area-editor"
          >
            <div class="text-area-header">
              <label>{{ textArea.placeholder }}</label>
              <div class="text-area-actions">
                <el-button 
                  text 
                  size="small"
                  @click="showTextStyler(index)"
                >
                  样式
                </el-button>
                <el-button 
                  text 
                  size="small"
                  type="danger"
                  @click="removeTextArea(index)"
                  v-if="textAreas.length > 1"
                >
                  删除
                </el-button>
              </div>
            </div>
            
            <el-input
              v-model="textArea.content"
              type="textarea"
              :rows="3"
              :placeholder="textArea.placeholder"
              @input="handleTextChange"
            />
            
            <!-- 文字样式控制 -->
            <div class="text-style-controls" v-if="textArea.showStyles">
              <div class="style-row">
                <label>字体大小:</label>
                <el-slider
                  v-model="textArea.fontSize"
                  :min="12"
                  :max="72"
                  :step="2"
                  show-input
                  @change="handleStyleChange"
                />
              </div>
              
              <div class="style-row">
                <label>字体颜色:</label>
                <el-color-picker 
                  v-model="textArea.color"
                  @change="handleStyleChange"
                />
              </div>
              
              <div class="style-row">
                <label>字体样式:</label>
                <el-checkbox-group v-model="textArea.fontStyles" @change="handleStyleChange">
                  <el-checkbox label="bold">粗体</el-checkbox>
                  <el-checkbox label="italic">斜体</el-checkbox>
                  <el-checkbox label="underline">下划线</el-checkbox>
                </el-checkbox-group>
              </div>
              
              <div class="style-row">
                <label>文字对齐:</label>
                <el-radio-group v-model="textArea.textAlign" @change="handleStyleChange">
                  <el-radio-button label="left">左对齐</el-radio-button>
                  <el-radio-button label="center">居中</el-radio-button>
                  <el-radio-button label="right">右对齐</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </div>
          
          <el-button 
            type="dashed" 
            class="add-text-btn"
            @click="addTextArea"
          >
            <el-icon><Plus /></el-icon>
            添加文字区域
          </el-button>
        </div>
      </div>
      
      <!-- 背景设置 -->
      <div class="content-section">
        <div class="section-header">
          <h4>背景设置</h4>
        </div>
        
        <div class="background-controls">
          <div class="control-row">
            <label>背景类型:</label>
            <el-radio-group v-model="backgroundType" @change="handleBackgroundChange">
              <el-radio-button label="color">纯色</el-radio-button>
              <el-radio-button label="gradient">渐变</el-radio-button>
              <el-radio-button label="image">图片</el-radio-button>
            </el-radio-group>
          </div>
          
          <div class="control-row" v-if="backgroundType === 'color'">
            <label>背景颜色:</label>
            <el-color-picker 
              v-model="backgroundColor"
              @change="handleBackgroundChange"
            />
          </div>
          
          <div class="control-row" v-if="backgroundType === 'gradient'">
            <label>渐变设置:</label>
            <div class="gradient-controls">
              <el-color-picker 
                v-model="gradientStart"
                @change="handleBackgroundChange"
              />
              <span>到</span>
              <el-color-picker 
                v-model="gradientEnd"
                @change="handleBackgroundChange"
              />
              <el-select v-model="gradientDirection" @change="handleBackgroundChange">
                <el-option label="从上到下" value="to bottom" />
                <el-option label="从左到右" value="to right" />
                <el-option label="对角线" value="45deg" />
              </el-select>
            </div>
          </div>
          
          <div class="control-row" v-if="backgroundType === 'image'">
            <label>背景图片:</label>
            <el-button @click="selectBackgroundImage">
              选择图片
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 图片选择器对话框 -->
    <el-dialog
      v-model="imageSelectorVisible"
      title="选择图片"
      width="80%"
    >
      <div class="image-selector-content">
        <div class="images-grid">
          <div
            v-for="image in availableImages"
            :key="image.id"
            class="image-option"
            :class="{ 'selected': selectedImage?.id === image.id }"
            @click="selectImage(image)"
          >
            <img :src="image.fileUrl" :alt="image.originalName" />
            <div class="image-option-info">
              <div class="image-option-name">{{ image.originalName }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="imageSelectorVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmImageSelection">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 文案生成器对话框 -->
    <el-dialog
      v-model="textGeneratorVisible"
      title="AI文案生成"
      width="600px"
    >
      <div class="text-generator-content">
        <el-form :model="textGenConfig" label-width="100px">
          <el-form-item label="文案类型">
            <el-radio-group v-model="textGenConfig.contentType">
              <el-radio-button label="SHORT">短句</el-radio-button>
              <el-radio-button label="LONG">长句</el-radio-button>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="文案风格">
            <el-radio-group v-model="textGenConfig.styleType">
              <el-radio-button label="PROMOTIONAL">营销</el-radio-button>
              <el-radio-button label="WARM">温馨</el-radio-button>
              <el-radio-button label="PROFESSIONAL">专业</el-radio-button>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="自定义提示">
            <el-input
              v-model="textGenConfig.customPrompt"
              type="textarea"
              :rows="3"
              placeholder="输入自定义提示词..."
            />
          </el-form-item>
        </el-form>
        
        <div class="generated-texts" v-if="generatedTexts.length > 0">
          <h4>生成结果:</h4>
          <div
            v-for="(text, index) in generatedTexts"
            :key="index"
            class="generated-text-item"
            @click="useGeneratedText(text)"
          >
            {{ text }}
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="textGeneratorVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="generateText"
          :loading="generatingText"
        >
          {{ generatingText ? '生成中...' : '生成文案' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, View, Plus } from '@element-plus/icons-vue'
import type { ImageModel, TextContentModel } from '@/types'

interface TextArea {
  placeholder: string
  content: string
  fontSize: number
  color: string
  fontStyles: string[]
  textAlign: string
  showStyles: boolean
}

interface Props {
  selectedImage?: ImageModel
  availableImages?: ImageModel[]
  template?: any
}

interface Emits {
  (e: 'image-change', image: ImageModel): void
  (e: 'text-change', textAreas: TextArea[]): void
  (e: 'style-change'): void
  (e: 'background-change', background: any): void
  (e: 'preview-toggle', show: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const showPreview = ref(true)
const imageSelectorVisible = ref(false)
const textGeneratorVisible = ref(false)
const generatingText = ref(false)
const generatedTexts = ref<string[]>([])

const textAreas = ref<TextArea[]>([
  {
    placeholder: '主标题',
    content: '',
    fontSize: 24,
    color: '#000000',
    fontStyles: [],
    textAlign: 'center',
    showStyles: false
  }
])

const backgroundType = ref('color')
const backgroundColor = ref('#ffffff')
const gradientStart = ref('#ffffff')
const gradientEnd = ref('#000000')
const gradientDirection = ref('to bottom')

const textGenConfig = reactive({
  contentType: 'SHORT',
  styleType: 'PROMOTIONAL',
  customPrompt: ''
})

// 监听模板变化
watch(() => props.template, (newTemplate) => {
  if (newTemplate) {
    // 根据模板初始化文字区域
    textAreas.value = newTemplate.layout.textAreas.map((area: any) => ({
      placeholder: area.placeholder,
      content: '',
      fontSize: parseInt(area.style.fontSize) || 24,
      color: area.style.color || '#000000',
      fontStyles: [],
      textAlign: area.style.textAlign || 'center',
      showStyles: false
    }))
    
    backgroundColor.value = newTemplate.backgroundColor
  }
}, { immediate: true })

// 方法
const togglePreview = () => {
  showPreview.value = !showPreview.value
  emit('preview-toggle', showPreview.value)
}

const showImageSelector = () => {
  imageSelectorVisible.value = true
}

const selectImage = (image: ImageModel) => {
  // 临时选择，等待确认
}

const confirmImageSelection = () => {
  imageSelectorVisible.value = false
  // emit('image-change', selectedImage)
}

const showTextGenerator = () => {
  if (!props.selectedImage) {
    ElMessage.warning('请先选择图片')
    return
  }
  textGeneratorVisible.value = true
}

const generateText = async () => {
  if (!props.selectedImage) return
  
  generatingText.value = true
  
  try {
    // 模拟AI文案生成
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    generatedTexts.value = [
      '精彩生活，从这里开始',
      '发现美好，分享快乐',
      '让每一刻都值得纪念',
      '品质生活，精致选择'
    ]
    
    ElMessage.success('文案生成成功')
  } catch (error) {
    ElMessage.error('文案生成失败')
  } finally {
    generatingText.value = false
  }
}

const useGeneratedText = (text: string) => {
  if (textAreas.value.length > 0) {
    textAreas.value[0].content = text
    handleTextChange()
  }
  textGeneratorVisible.value = false
}

const showTextStyler = (index: number) => {
  textAreas.value[index].showStyles = !textAreas.value[index].showStyles
}

const addTextArea = () => {
  textAreas.value.push({
    placeholder: `文字区域 ${textAreas.value.length + 1}`,
    content: '',
    fontSize: 16,
    color: '#000000',
    fontStyles: [],
    textAlign: 'center',
    showStyles: false
  })
  handleTextChange()
}

const removeTextArea = (index: number) => {
  textAreas.value.splice(index, 1)
  handleTextChange()
}

const handleTextChange = () => {
  emit('text-change', textAreas.value)
}

const handleStyleChange = () => {
  emit('style-change')
}

const handleBackgroundChange = () => {
  let background: any = {}
  
  switch (backgroundType.value) {
    case 'color':
      background = { type: 'color', value: backgroundColor.value }
      break
    case 'gradient':
      background = {
        type: 'gradient',
        start: gradientStart.value,
        end: gradientEnd.value,
        direction: gradientDirection.value
      }
      break
    case 'image':
      background = { type: 'image', value: '' }
      break
  }
  
  emit('background-change', background)
}

const selectBackgroundImage = () => {
  ElMessage.info('背景图片选择功能开发中...')
}
</script>

<style scoped>
.content-editor {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 20px;
  color: white;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.editor-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.editor-content {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.content-section {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

/* 图片选择样式 */
.image-selection {
  display: flex;
  justify-content: center;
}

.selected-image-card {
  display: flex;
  align-items: center;
  gap: 15px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  padding: 15px;
  max-width: 300px;
}

.selected-image-card img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
}

.image-info {
  flex: 1;
}

.image-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 5px;
}

.image-size {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.no-image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px;
  width: 200px;
  height: 120px;
  border: 2px dashed rgba(255, 255, 255, 0.3);
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.no-image-placeholder:hover {
  border-color: rgba(255, 255, 255, 0.5);
  background: rgba(255, 255, 255, 0.05);
}

/* 文字区域样式 */
.text-areas {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.text-area-editor {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  padding: 15px;
}

.text-area-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.text-area-header label {
  font-size: 14px;
  font-weight: 500;
}

.text-area-actions {
  display: flex;
  gap: 8px;
}

.text-style-controls {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.style-row {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.style-row label {
  min-width: 80px;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

.add-text-btn {
  border: 2px dashed rgba(255, 255, 255, 0.3);
  background: transparent;
  color: rgba(255, 255, 255, 0.8);
  height: 50px;
}

.add-text-btn:hover {
  border-color: rgba(255, 255, 255, 0.5);
  background: rgba(255, 255, 255, 0.05);
}

/* 背景控制样式 */
.background-controls {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.control-row {
  display: flex;
  align-items: center;
  gap: 15px;
}

.control-row label {
  min-width: 80px;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

.gradient-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 对话框样式 */
.image-selector-content {
  max-height: 400px;
  overflow-y: auto;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 15px;
}

.image-option {
  cursor: pointer;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.image-option:hover {
  transform: scale(1.05);
}

.image-option.selected {
  border: 2px solid #409EFF;
}

.image-option img {
  width: 100%;
  height: 80px;
  object-fit: cover;
}

.image-option-info {
  padding: 8px;
  background: #f5f5f5;
}

.image-option-name {
  font-size: 12px;
  color: #333;
  text-align: center;
}

.text-generator-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.generated-texts h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.generated-text-item {
  padding: 10px;
  background: #f8f9fa;
  border-radius: 5px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.generated-text-item:hover {
  background: #e9ecef;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-editor {
    padding: 15px;
  }
  
  .editor-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .style-row,
  .control-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .gradient-controls {
    flex-wrap: wrap;
  }
}
</style>